<script setup>
import Recorder from '@u/recorder.js'
import { useWebSocket } from '@vueuse/core'
const VITE_WS_URL = import.meta.env.VITE_WS_URL
const content = ref('');//录音识别内容
let ws = null;//websocket
let interval = null;//定时器
const isRecording = ref(false)
const visualizer = ref()
let recorder = new Recorder({
 sampleBits: 16,
 sampleRate: 16000,
 numChannels: 1,
 compiling:true,
 silentThreshold: 3,
});

// 录音
const startRecording = () =>{
    recorder.start().then(()=>{
        isRecording.value = true
        recorder.visualizeRecording(visualizer.value)
        console.log('开始录音');
        if(blob.value){
            startSendRecording()
        }
    }).catch((err)=>{
        isRecording.value = false
        console.log(err);
    });
}

// 停止录音
const stopRecording = () =>{
    recorder.stop()
    clearInterval(interval)
    isRecording.value = false
    if(blob.value){
        ws.send('finished')
    }
    console.log('停止录音');
}
const blob = ref(false)
// 开始发送录音
const startSendRecording = () =>{
    ws = useSocket()
    ws.send('ping')
    interval = setInterval(() => {
        let data = recorder.getNextData()    
        ws.send(data);
    }, 40)
}
recorder.onSilentDetected = (silentDuration) => {
    console.log(`静音超过 ${silentDuration} 秒`);
    recorder.stop(); // 停止录音
    clearInterval(interval)
    isRecording.value = false
    ws.send('finished')
    // recorder.clear()
};

// 使用websocket
const useSocket = () =>{
    const url = VITE_WS_URL+'/client/voice/websocket'
    // const url = 'ws://localhost:8090/msg'
    const {status, close, send, open, ws} = useWebSocket(url,{
        heartbeat:  {
            interval: 5000,
            pongTimeout: 3000,
        },
        onMessage(ws,event){
            console.log(event.data);
            if(event.data){
                console.log('event.data',event.data);
                
                content.value = event.data
            }
        },
        onDisconnect(ws,event){
            console.log('websocket连接关闭');
            recorder.stop()
            clearInterval(interval)
            isRecording.value = false
        },
        onError(ws,event){
            console.log('websocket连接错误');
            recorder.stop()
            clearInterval(interval)
            isRecording.value = false
        },
        onConnect(ws,event){
            console.log('websocket连接成功');
        }
    })
    return {status, close, send, open, ws}
}

// 播放录音
const playRecording = () =>{
    recorder.play()
}

// 清除内容
const clearContent = () => {
    content.value = '';
}

// 下载
const download = () =>{
    // recorder.downloadMP3()
    recorder.downloadPCM()
}
const fileInput = ref()
// 打印
const uploadFile = () =>{
    fileInput.value.click()
}
// 文件上传
const handleFileChange = (e) =>{
    const file = e.target.files[0]
    recorder.uploadAudioPlay(file)
    e.target.value = ''
    // console.log(e.target.files[0]);
}
onMounted(()=>{
    // console.log('onMounted');
    
})
</script>

<template>
  <div class="recorder">
    <div class="recorder-container">
        <div class="recorder-container-left">
            <canvas class="recorder-canvas" ref="visualizer" width="600" height="200"></canvas>
            <!-- <div class="recorder-canvas" ref="visualizer" ></div> -->
            <div class="recorder-button-container">
                <label> <input type="checkbox" v-model="blob"> 是否发送数据</label>
                <button class="recorder-button" @click="isRecording ? stopRecording() : startRecording()">
                {{ isRecording ? '停止录音' : '开始录音' }}
                </button>
                <button :class="['recorder-button', isRecording ? 'recorder-button-play' : '']" :disabled="isRecording" @click="playRecording">
                    播放
                </button>
                <button class="recorder-button" @click="download">下载</button>
            </div>
        </div>
        <div class="recorder-container-right">
            <div class="recorder-content-header">
                <h1 class="recorder-content-title">录音识别内容</h1>
                <button class="recorder-button" @click="clearContent">
                    清除内容
                </button>
            </div>
            <div class="recorder-content">
                <textarea class="recorder-textarea" placeholder="录音识别内容" readonly :value="content"></textarea>
            </div>
        </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.recorder {
    width: 100%;
    height: 100%;
    padding: 20px 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    // 手机端
    @media (max-width: 768px) {
        width: 100%;
        height: 100%;
        overflow-y: scroll;
    }
    .recorder-container {
        display: flex;
        flex-direction: row;
        height: 100%;
        gap: 20px;
        padding: 0 20px 20px;
        box-sizing: border-box;
        // Adjust for mobile
        @media (max-width: 768px) {
            flex-direction: column;
            padding: 10px;
        }
        .recorder-container-left {
            display: flex;
            flex-direction: column;
            .recorder-canvas {
                border: 1px solid #ccc;
                margin-bottom: 20px;
                // 手机端
                @media (max-width: 768px) {
                    width: 100%;
                }
            }
            .recorder-button-container {
                display: flex;
                gap: 20px;
                // 手机端
                @media (max-width: 768px) {
                    flex-wrap: wrap;
                    gap: 10px;
                }
                .recorder-button {
                    width: 120px;
                    height: 50px;
                    padding: 10px 20px;
                    font-size: 16px;
                    border: 1px solid #ccc;
                    border-radius: 5px;
                    background-color: #fff;
                    cursor: pointer;
                    @media (max-width: 768px) {
                        width: 100px;
                        height: 40px;
                        font-size: 14px;
                    }
                }
            }
        }
        .recorder-container-right {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #ccc;
            .recorder-content-header {
                margin: 10px 0;
                padding: 0 30px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 30px;
                line-height: 30px;
                box-sizing: border-box;
                .recorder-content-title {
                    font-size: 20px;
                    text-shadow: 2px 2px 1px rgba(0, 0, 0, 0.2);
                }
                .recorder-button {
                    width: 100px;
                    height: 30px;
                    padding: 0 20px;
                    font-size: 14px;
                    border: 1px solid #ccc;
                    border-radius: 5px;
                    background-color: #fff;
                    cursor: pointer;
                }
            }
            .recorder-content {
                flex: 1;
                .recorder-textarea {
                    width: 100%;
                    height: 100%;
                    border: 1px solid #ccc;
                    outline: none;
                    resize: none;
                    padding: 10px;
                    box-sizing: border-box;
                }
            }
        }
    }
}
</style>